import 'package:OASys/api/EventApi.dart';
import 'package:OASys/api/UserApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/components/scaffoldItem.dart';
import 'package:OASys/entity/EventVo.dart';
import 'package:OASys/entity/UserVo.dart';
import 'package:OASys/utils/strUtils.dart';
import 'package:flutter/material.dart';

class EventEditPage extends StatelessWidget {
  final Map arguments;

  EventEditPage({Key key, this.arguments});
  @override
  Widget build(BuildContext context) {
    return ScaffoldItem(
        '流程信息',
        MyEventEditPage(
          eventId: arguments['info'] == null ? -1 : arguments['info']['id'],
          isEdit: arguments['isEdit'],
        ));
  }
}

class MyEventEditPage extends StatefulWidget {
  final int eventId;
  final bool isEdit;

  MyEventEditPage({Key key, this.eventId, this.isEdit});
  @override
  _MyEventEditPageState createState() => _MyEventEditPageState();
}

class _MyEventEditPageState extends State<MyEventEditPage> {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();

  EventVo eventVo;
  EventVo info;
  List<Map<String, dynamic>> parentList = [];
  List<UserVo> userList = [];
  List<int> ids = [];
  List<UserVo> participantList = [];
  List<Map<String, dynamic>> typeList = [];

  DateTime beginDay;
  DateTime overDay;
  TimeOfDay beginTime;
  TimeOfDay overTime;
  bool enabled;

  @override
  void initState() {
    super.initState();
    enabled = widget.isEdit;
    getUserList();
    buildTypeList();
    if (widget.eventId == -1) {
      setState(() {
        info = new EventVo();
        eventVo = new EventVo();
      });
    } else {
      getEventInfo(widget.eventId);
    }
  }

  void buildTypeList() {
    setState(() {
      typeList.add({"key": 0, "value": "病假"});
      typeList.add({"key": 1, "value": "事假"});
      typeList.add({"key": 2, "value": "公假"});
      typeList.add({"key": 3, "value": "产假"});
      typeList.add({"key": 4, "value": "丧假"});
      typeList.add({"key": 5, "value": "年假"});
      typeList.add({"key": 6, "value": "报销"});
      typeList.add({"key": 7, "value": "采购"});
      typeList.add({"key": 8, "value": "物品租借"});
      typeList.add({"key": 9, "value": "入职审批"});
      typeList.add({"key": 10, "value": "立项审批"});
    });
  }

  void getUserList() {
    UserApi().list(
      1,
      1000,
      success: (res) {
        setState(() {
          userList = res;
          bulidParentList(userList);
        });
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  void getEventInfo(int id) {
    EventApi().getInfo(
      id,
      success: (res) {
        setState(() {
          eventVo = EventVo.fromJson(res.toJson());
          if (eventVo.status != 0) {
            enabled = false;
          }
          info = res;
          beginDay = DateTime.parse(info.beginTime);
          overDay = DateTime.parse(info.overTime);
          beginTime = TimeOfDay.fromDateTime(DateTime.parse(info.beginTime));
          overTime = TimeOfDay.fromDateTime(DateTime.parse(info.overTime));
        });
        print(res.toJson().toString());
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  //保存操作
  void save() {
    var form = formKey.currentState;
    String begin = bulidDayStr(beginDay) + " " + bulidTimeStr(beginTime);
    String over = bulidDayStr(overDay) + " " + bulidTimeStr(overTime);
    if (form.validate()) {
      form.save();
      if (DateTime.parse(begin).isAfter(DateTime.now())) {
        if (DateTime.parse(begin).isBefore(DateTime.parse(over))) {
          setState(() {
            info.beginTime = begin;
            info.overTime = over;
            print(info.toJson());
            doSave(info);
          });
        } else {
          showMessage(context, "会议开始时间不得提前于结束时间");
        }
      } else {
        showMessage(context, "会议日期不得提前于当前日期");
      }
    }
  }

  // 发起保存请求
  void doSave(EventVo info) {
    print('doSave');
    EventApi().save(
      info,
      success: (res) {
        Navigator.of(context).pop(true);
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  // 构建所有用户列表
  void bulidParentList(List<UserVo> list) {
    setState(() {
      parentList = [];
      list.forEach((element) {
        parentList.add({"key": element.id, "value": element.nickname});
      });
    });
  }

  // 重置表单
  void reset() {
    var form = formKey.currentState;
    form.reset();
    setState(() {
      info.type = int.parse(eventVo.type.toString());
      info.typeName = eventVo.typeName;
      info.userId = eventVo.userId;
      beginDay = DateTime.parse(info.beginTime);
      overDay = DateTime.parse(info.overTime);
      beginTime = TimeOfDay.fromDateTime(DateTime.parse(info.beginTime));
      overTime = TimeOfDay.fromDateTime(DateTime.parse(info.overTime));
    });
  }

  // 单选框
  selectOne() {
    showOneSelect(context, info.type);
  }

  selectChecker() {
    showCheckerSelect(context, info.checkerId);
  }

  // 构建时间字符串 用于显示
  String bulidTimeStr(TimeOfDay time) {
    String hour =
        time.hour < 10 ? "0" + time.hour.toString() : time.hour.toString();
    String minute = time.minute < 10
        ? "0" + time.minute.toString()
        : time.minute.toString();
    return hour + ":" + minute + ":00";
  }

  // 构建日期字符串 用于显示
  String bulidDayStr(DateTime dateTime) {
    return dateTime.toString().substring(0, 10);
  }

  @override
  Widget build(BuildContext context) {
    if (info == null || eventVo == null) {
      return Container(
        child: Text('加载中'),
      );
    } else {
      return SingleChildScrollView(
        child: Container(
          width: 500,
          margin: EdgeInsets.all(10),
          child: Card(
            child: Container(
              margin: EdgeInsets.all(10),
              child: Form(
                key: formKey,
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('流程名称：'),
                        FormInput(
                          enabled: enabled,
                          initValue: eventVo.name,
                          hintText: "请输入流程名称",
                          validator: (content) {
                            if (content.length > 12) {
                              return "流程名过长";
                            } else if (content.length <= 0) {
                              return "流程名过短";
                            }
                          },
                          onSave: (value) {
                            info.name = value;
                          },
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('流程类型：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () {
                              if (!enabled) {
                                return;
                              }
                              if (info.status != 0 && info.status != null) {
                                return;
                              }
                              selectOne();
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                info.type == null ? "请选择会议类型" : info.typeName,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('流程内容：'),
                        FormText(
                          enabled: enabled,
                          initValue: eventVo.content,
                          hintText: "请输入流程内容",
                          validator: (content) {
                            if (content.length > 50) {
                              return "流程内容过长";
                            } else if (content.length <= 0) {
                              return "流程内容过短";
                            }
                          },
                          onSave: (value) {
                            info.content = value;
                          },
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('流程开始日期：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () async {
                              if (!enabled) {
                                return;
                              }
                              if (info.status != 0 && info.status != null) {
                                return;
                              }
                              DateTime result = await showDatePicker(
                                context: context,
                                initialDate: beginDay == null
                                    ? DateTime.now()
                                    : beginDay,
                                firstDate: DateTime(DateTime.now().year),
                                lastDate: DateTime(2035),
                                helpText: "选择开始日期",
                                cancelText: "取消",
                                confirmText: "保存",
                              );
                              if (result != null) {
                                setState(() {
                                  beginDay = result;
                                });
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                beginDay == null
                                    ? "请选择开始日期"
                                    : beginDay.toString().substring(0, 10),
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('开始时间：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () async {
                              if (!enabled) {
                                return;
                              }
                              if (info.status != 0 && info.status != null) {
                                return;
                              }
                              var result = await showTimePicker(
                                context: context,
                                initialTime: TimeOfDay.now(),
                                builder: (BuildContext context, Widget child) {
                                  return MediaQuery(
                                    data: MediaQuery.of(context)
                                        .copyWith(alwaysUse24HourFormat: true),
                                    child: child,
                                  );
                                },
                                helpText: "选择开始时间",
                                cancelText: "取消",
                                confirmText: "保存",
                              );
                              if (result != null) {
                                setState(() {
                                  beginTime = result;
                                });
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                beginTime == null
                                    ? "请选择开始时间"
                                    : bulidTimeStr(beginTime),
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('流程结束日期：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () async {
                              if (!enabled) {
                                return;
                              }
                              if (info.status != 0 && info.status != null) {
                                return;
                              }
                              DateTime result = await showDatePicker(
                                context: context,
                                initialDate:
                                    overDay == null ? DateTime.now() : overDay,
                                firstDate: DateTime(DateTime.now().year),
                                lastDate: DateTime(2035),
                                helpText: "选择结束日期",
                                cancelText: "取消",
                                confirmText: "保存",
                              );
                              if (result != null) {
                                setState(() {
                                  overDay = result;
                                });
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                overDay == null
                                    ? "请选择结束日期"
                                    : overDay.toString().substring(0, 10),
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('结束时间：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () async {
                              if (!enabled) {
                                return;
                              }
                              if (info.status != 0 && info.status != null) {
                                return;
                              }
                              var result = await showTimePicker(
                                context: context,
                                initialTime: overTime == null
                                    ? TimeOfDay.now()
                                    : overTime,
                                builder: (BuildContext context, Widget child) {
                                  return MediaQuery(
                                    data: MediaQuery.of(context)
                                        .copyWith(alwaysUse24HourFormat: true),
                                    child: child,
                                  );
                                },
                                helpText: "选择结束时间",
                                cancelText: "取消",
                                confirmText: "保存",
                              );
                              if (result != null) {
                                setState(() {
                                  overTime = result;
                                });
                              }
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                overTime == null
                                    ? "请选择结束时间"
                                    : bulidTimeStr(overTime),
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('流程审核者：'),
                        Container(
                          width: 200,
                          child: FlatButton(
                            onPressed: () {
                              if (!enabled) {
                                return;
                              }
                              if (info.status != 0 && info.status != null) {
                                return;
                              }
                              selectChecker();
                            },
                            child: Text(StrUtils.isNotBlank(info.checkerName)
                                ? info.checkerName
                                : "请选择审核者"),
                          ),
                        ),
                      ],
                    ),
                    Visibility(
                      visible: info.status != 0 && info.status != null,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          PrefixContanier('审批回复：'),
                          FormText(
                            initValue: eventVo.checkContent,
                            enabled: false,
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      height: 30,
                    ),
                    Visibility(
                      visible: enabled,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          RaisedButton(
                            color: Color.fromRGBO(33, 150, 243, 1),
                            onPressed: save,
                            child: Text(
                              "保 存",
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          RaisedButton(
                            color: Color.fromRGBO(103, 194, 58, 1),
                            onPressed: reset,
                            child: Text(
                              "重 置",
                              style: TextStyle(color: Colors.white),
                            ),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
    }
  }

  // 显示单选
  showOneSelect(BuildContext context, int oldType) {
    int type = oldType;
    String typeName;

    Widget bulidListItem(int index, StateSetter setState) {
      return Row(
        children: [
          Flexible(
            child: RadioListTile(
              title: Text(typeList[index]["value"]),
              value: index,
              groupValue: type,
              onChanged: (value) {
                setState(() {
                  type = value;
                  typeName = typeList[index]["value"];
                  info.type = value;
                  info.typeName = typeList[index]["value"];
                });
              },
            ),
          ),
        ],
      );
    }

    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            titlePadding: EdgeInsets.all(0),
            title: Container(
              height: 50,
              alignment: Alignment.center,
              child: Text(
                '会议类型选择',
                style: TextStyle(color: Colors.white),
              ),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(3),
                  topRight: Radius.circular(3),
                ),
              ),
            ),
            contentPadding: EdgeInsets.all(0),
            content: new StatefulBuilder(
              builder: (context, StateSetter setState) {
                return Container(
                  height: 300,
                  width: 300,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(250, 250, 250, 1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Column(
                    children: [
                      Container(
                        margin: EdgeInsets.only(
                          top: 20,
                          bottom: 20,
                        ),
                        height: 260,
                        width: 200,
                        child: ListView.builder(
                            itemCount: typeList.length,
                            itemBuilder: (context, index) {
                              return bulidListItem(index, setState);
                            }),
                      ),
                    ],
                  ),
                );
              },
            ),
            actions: <Widget>[
              RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text("保 存"),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        }).then((value) {
      print(value);
      if (value != null && value) {
        setState(() {
          info.type = type;
          info.typeName = typeName;
        });
      }
    });
  }

  showCheckerSelect(BuildContext context, int oldId) {
    int checkerId = oldId;
    String checkerName;

    Widget bulidListItem(int index, StateSetter setState) {
      return Row(
        children: [
          Flexible(
            child: RadioListTile(
              title: Text(parentList[index]["value"]),
              value: parentList[index]['key'],
              groupValue: checkerId,
              onChanged: (value) {
                setState(() {
                  checkerId = value;
                  checkerName = parentList[index]["value"];
                  info.checkerId = value;
                  info.checkerName = parentList[index]["value"];
                });
              },
            ),
          ),
        ],
      );
    }

    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            titlePadding: EdgeInsets.all(0),
            title: Container(
              height: 50,
              alignment: Alignment.center,
              child: Text(
                '会议类型选择',
                style: TextStyle(color: Colors.white),
              ),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(3),
                  topRight: Radius.circular(3),
                ),
              ),
            ),
            contentPadding: EdgeInsets.all(0),
            content: new StatefulBuilder(
              builder: (context, StateSetter setState) {
                return Container(
                  height: 300,
                  width: 300,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(250, 250, 250, 1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Column(
                    children: [
                      Container(
                        margin: EdgeInsets.only(
                          top: 20,
                          bottom: 20,
                        ),
                        height: 260,
                        width: 200,
                        child: ListView.builder(
                            itemCount: typeList.length,
                            itemBuilder: (context, index) {
                              return bulidListItem(index, setState);
                            }),
                      ),
                    ],
                  ),
                );
              },
            ),
            actions: <Widget>[
              RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text("保 存"),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        }).then((value) {
      print(value);
      if (value != null && value) {
        setState(() {
          info.checkerId = checkerId;
          info.checkerName = checkerName;
        });
      }
    });
  }
}
